﻿
using System;
using System.IO;
using System.Collections;
using System.Collections.Generic;
using System.Net;
using System.Reflection;
using System.Diagnostics;
using System.Text;
using System.Linq;
using System.Text.RegularExpressions;
using System.Windows.Forms;
using System.Security.Cryptography;
using Region.Forms;
using Region.Properties;
using System.IO.Pipes;
using Region.Test;
using Region.Utils;
using System.Threading;

namespace Region
{    

    class Notify
    {
      Engine m_engine;
      NotifyIcon m_notifyIcon;
      NamedPipeServerStream m_pipe;
      public void ConnectionCallback(IAsyncResult ar)
      { 
        //NamedPipeServerStream pipeServer = (NamedPipeServerStream)ar.AsyncState;                
        this.m_pipe.EndWaitForConnection(ar);
        byte[] Buff = new Byte[1024];
        int n = m_pipe.Read(Buff,0,1024);
      }
      public bool StartServer()      
      {
        try{ m_pipe = new NamedPipeServerStream("RPN_Region.Command", PipeDirection.InOut,1,PipeTransmissionMode.Byte,PipeOptions.Asynchronous);}
        catch(System.UnauthorizedAccessException){return false;}
        m_pipe.BeginWaitForConnection(new AsyncCallback(ConnectionCallback),this);
        NamedPipeClientStream pipe1 = new NamedPipeClientStream("RPN_Region.Command");
        pipe1.Connect();
        pipe1.Write(Encoding.UTF8.GetBytes("Test"),0,4);
        return true;
      }
      public bool Show()
      {      
        if (m_notifyIcon==null) m_notifyIcon = new NotifyIcon();
        
        m_notifyIcon.Icon = System.Drawing.Icon.FromHandle(Resources.Dir.GetHicon());
        m_notifyIcon.Visible = true;
        m_notifyIcon.Text = "Antivirus program";
        return true;
      }
      public Notify(Engine engine)
      {
        m_engine = engine;
        
      }
    }
}

namespace Region
{
    static class Program
    {
      public  static String RegionDir;
      static Stream GetStreamURI(String Link){return GetStreamURI(new Uri(Link));}
      static Stream GetStreamURI(Uri Link)
      {
        if (Link.Scheme.ToLower()=="http")
        {
          var Web = WebRequest.Create(Link);
          Web.Credentials = CredentialCache.DefaultCredentials;
          var resp = Web.GetResponse();
          return resp.GetResponseStream();
        }
        return null;
      }
      static String GetStringURI(String Link){return GetStringURI(new Uri(Link));}
      static String GetStringURI(Uri Link)
      {
        using(Stream stream = GetStreamURI(Link))
        {
          StreamReader reader = new StreamReader(stream,Encoding.UTF8);
          return reader.ReadToEnd();          
        }        
      }
      static Byte[] GetDataURI(String Link){return GetDataURI(new Uri(Link));}
      static Byte[] GetDataURI(Uri Link)
      {
        using(Stream stream = GetStreamURI(Link))
        {
          Byte[] Buff = new Byte[stream.Length];
          stream.Read(Buff,0,(Int32)stream.Length);
          return Buff;
        }        
      }
      static bool Update(String Link)
      {
        try
        {
          if (!File.Exists("./Version")) return false;// Необновлять так как нет файла версии(отладка)
          String CurrentVersion = Encoding.UTF8.GetString(File.ReadAllBytes("./Version"));        
          String NewVersion =  GetStringURI(Link+"Version");
          if (NewVersion==CurrentVersion) return false;// Обновление не требуется
          Zip PacketZip = new Zip();
          using(Stream stream = GetStreamURI(Link+"Region"+NewVersion+".zip"))
          {            
            //Обновить программу обновления
            /*if (File.Exists("./Updater.exe")) File.Delete("./Updater.exe");
            PacketZip.readZIP(stream);
            Byte[] Updater = PacketZip.readAll("Updater.exe");
            using(FileStream SaveFile = File.Create("./Updater.exe")) SaveFile.Write(Updater,0,Updater.Length);*/
            while(Process.GetProcessesByName("UpRegion2").Length>0) Thread.Sleep(100);
            if (File.Exists("./UpRegion2.exe")) File.Delete("./UpRegion2.exe");
            File.Copy("./Updater.exe","./UpRegion2.exe");
            //Сохранить пакет обновления на диск
            if (File.Exists("./Packet.zip")) File.Delete("./Packet.zip");
            Int32 Count=0;
            Byte[] Buff = new Byte[1024*128];
            using(FileStream Packet = File.Create("./Packet.zip"))
            {
              do
              {
                Count = stream.Read(Buff,0,Buff.Length);              
                if (Count>0) Packet.Write(Buff,0,Count);
              }
              while(Count>0);
            }
            Process.Start("UpRegion2.exe","--run Region2 --wait Region2 --unpack ./Packet.zip .");            
            return true;
          }
        }
        catch(System.Net.ProtocolViolationException){}
        catch(System.Net.WebException){}
        catch(Exception E){MessageBox.Show("Update exception: "+E.Message);}
        
        //u.Scheme
        return false;
      }
      static void TestExportRasporList(Engine E)
      {
        var RL =  new RasporList(E);
        RL.setWhere("RasporYear",2013);
        RL.setWhere("Page",1);
        RL.setWhere("LineInPage",100);
        RL.Filter();
        RL.ExportListXMLX(@"F:\Reest.xlsx");
      } 
      static void TestExportKontList(Engine E)
      {
        var RL =  new KontList(E);
        //RL.setWhere("RasporYear",2013);
        RL.setWhere("Page",1);
        RL.setWhere("LineInPage",100);
        RL.Filter();
        RL.ExportListXMLX(@"F:\ReestKont.xlsx");
      }  
    /// <summary>
    /// Главная точка входа для приложения.
    /// </summary>
    [STAThread]
    static void Main(string[] args)
    {

      /*var T = new Forms.TestForm(null);
          T.ShowDialog();
          return;/**/
       
      RegionDir = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) + "/Region2";      
      var t = new DirectoryInfo(RegionDir);
      
      if (args.Contains("--PrivateOnly") || args.Contains("-po"))
      {
        using(var engine = new Engine())
        {
          
          var root = new DirFIO(engine, "Персональные данные", "");
          engine.LoginFIO();
          Application.Run(new BrowserForm(engine, root, false));
        }
      }
      else if (args.Contains("--Update") || args.Contains("-u"))
      {
        Console.WriteLine("Обновление");
        if (Update(@"http://192.168.0.19/Region2/")) return;
        Console.WriteLine("Обновлено");
      }
      else if (args.Contains("--help") || args.Contains("-h"))
      { 
        Console.WriteLine("region2 [--PrivateOnly|--help]");
        Console.WriteLine("--PrivateOnly или -po Вывести раздел по персональным данным");
      }
      else/**/       
      //try
      {
        //bool t = Test.Test1.Test();
        if (Update(@"http://192.168.0.19/Region2/")) return;
        Application.EnableVisualStyles();
        Application.SetCompatibleTextRenderingDefault(false);
        /*new Utils.ExportTest(); return;/**/
        if (!Directory.Exists(RegionDir)) Directory.CreateDirectory(RegionDir);
        var default_config = new Utils.XMLConfig("default_config.xml");
        var config = new Utils.XMLConfig(RegionDir+"/config.xml",default_config);        
        using(var engine = new Engine(config))
        {
          engine.OnShowTask+=()=>{new Forms.TaskWait(engine).ShowDialog();};
          SQLView sv = null ;
          if (args.Contains("--debugsqlview"))
          {
            sv = new SQLView(engine);
          }
          engine.LoginPDn();
          engine.LoginFIO();
          var A = new Forms.Auth(engine);
          A.ShowDialog();
          if (!A.Result) return;
          if (sv != null) sv.Show();


          var root = new DirItem(); 
          root.setData(0, "Caption", "Регион");
          root.Add(new DirReestrAuto(engine,"Автотранспорт",""));
          
          if (engine.isAccess("EditRaspor")) 
            root.Add(new DirReestrRaspor(engine,"Распоряжения",""));
          if (engine.isAccess("EditRaspor")) 
            root.Add(new DirReestrPoruch(engine,"Поручения",""));
          if (engine.isAccess("KontEdit"))
            root.Add(new DirReestrKont(engine,"Контрагенты",""));
          if (engine.isAccess("Yurist"))
            root.Add(new DirReestrProtokol(engine,"Протоколы",""));
          if (engine.isAccess("EditRaspor"))
            root.Add(new DirReestrReport(engine,"Отчёты",""));
          /*if (engine.isAccess("EditRaspor"))
            root.Add(new DirReestrPred(engine,"Предписания ФБУЗ",""));*/
          if (engine.isAccess("KontEdit"))
            root.Add(new DirReestrIP(engine, "ПД ИП", ""));
          root.Add(new DirFIO(engine, "Персональные данные", ""));
          Application.Run(new BrowserForm(engine, root, false));
        }
        config.save();
      }
      /*catch(Exception E)
      {MessageBox.Show(E.Message);}*/
    }
  }
}
